//
//  ZLHXHelper.m
//  EnjoyAll
//
//  Created by 王晓冰 on 2017/10/30.
//  Copyright © 2017年 张雷. All rights reserved.
//

#import "ZLHXHelper.h"
#import "ZLSimple.h"
#import "MJExtension.h"
#import <UserNotifications/UserNotifications.h>

@implementation ZLHXHelper
+ (void)loginHXWithPw:(NSString *)pw{

    @WeakObj(self);
    [[EMClient sharedClient] loginWithUsername:[DataCenter shareInstence].loginName
                                      password:pw
                                    completion:^(NSString *aUsername, EMError *aError) {
                                        
                  
                                        if (!aError) {
                                            //设置是否自动登录
                                            [[EMClient sharedClient].options setIsAutoLogin:YES];
                                            //发送自动登陆状态通知
                                            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
                                            iToast *itoast = [[iToast alloc]initWithText:@"环信登录成功"];
                                            [itoast show];
                                            
                                            //设置通知显示
                                            [ZLHXHelper setNoti];
                                        } else {
                                            
                                            iToast *itoast = [[iToast alloc]initWithText:@"环信登录失败"];
                                            [itoast show];
                                        }
                                    }];
    
}





+ (void)easeUIApplication:(UIApplication *)application withOptions:(NSDictionary *)launchOptions {
    
    [[EaseSDKHelper shareHelper] hyphenateApplication:application
                        didFinishLaunchingWithOptions:launchOptions
                                               appkey:KHXKey
                                         apnsCertName:KHXCer
                                          otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
}

+ (void)setNoti {
    
//    //获取服务器属性
//    EMError *error = nil;
//    EMPushOptions *options = [[EMClient sharedClient] getPushOptionsFromServerWithError:&error];
    
    //设置推送详情
    EMPushOptions *options = [[EMClient sharedClient] pushOptions];
    options.displayStyle = EMPushDisplayStyleMessageSummary; // 显示消息内容
    // options.displayStyle = EMPushDisplayStyleSimpleBanner // 显示“您有一条新消息”
    EMError *error = [[EMClient sharedClient] updatePushOptionsToServer]; // 更新配置到服务器，该方法为同步方法，如果需要，请放到单独线程
    if(!error) {
        // 成功
    }else {
        // 失败
    }
}

+ (void)registerNoti {
    
    UIApplication *application = [UIApplication sharedApplication];
    
    //iOS10 注册APNs
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        
        if (@available(iOS 10.0, *)) {
            
            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *error) {
                if (granted) {
#if !TARGET_IPHONE_SIMULATOR
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[UIApplication sharedApplication] registerForRemoteNotifications];
                    });
                    //                [application registerForRemoteNotifications];
#endif
                }
            }];
            return;
        } else {
            // Fallback on earlier versions
        }
        
    }
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
#if !TARGET_IPHONE_SIMULATOR
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
#endif
}

+ (void)receiveMessage:(NSArray *)aMessages {
    
    
    for (EMMessage *message in aMessages) {
        EMMessageBody *msgBody = message.body;
        switch (msgBody.type) {
            case EMMessageBodyTypeText:
            {
                // 收到的文字消息
                EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                NSString *txt = textBody.text;
                NSLog(@"收到的文字是 txt -- %@",txt);
            }
                break;
            case EMMessageBodyTypeImage:
            {
                // 得到一个图片消息body
                EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
                NSLog(@"大图remote路径 -- %@"   ,body.remotePath);
                NSLog(@"大图local路径 -- %@"    ,body.localPath); // // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"大图的secret -- %@"    ,body.secretKey);
                NSLog(@"大图的W -- %f ,大图的H -- %f",body.size.width,body.size.height);
                NSLog(@"大图的下载状态 -- %u",body.downloadStatus);
                
                // 缩略图sdk会自动下载
                NSLog(@"小图remote路径 -- %@"   ,body.thumbnailRemotePath);
                NSLog(@"小图local路径 -- %@"    ,body.thumbnailLocalPath);
                NSLog(@"小图的secret -- %@"    ,body.thumbnailSecretKey);
                NSLog(@"小图的W -- %f ,大图的H -- %f",body.thumbnailSize.width,body.thumbnailSize.height);
                NSLog(@"小图的下载状态 -- %u",body.thumbnailDownloadStatus);
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                EMLocationMessageBody *body = (EMLocationMessageBody *)msgBody;
                NSLog(@"纬度-- %f",body.latitude);
                NSLog(@"经度-- %f",body.longitude);
                NSLog(@"地址-- %@",body.address);
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                // 音频sdk会自动下载
                EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
                NSLog(@"音频remote路径 -- %@"      ,body.remotePath);
                NSLog(@"音频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在（音频会自动调用）
                NSLog(@"音频的secret -- %@"        ,body.secretKey);
                NSLog(@"音频文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"音频文件的下载状态 -- %u"   ,body.downloadStatus);
                NSLog(@"音频的时间长度 -- %d"      ,body.duration);
            }
                break;
            case EMMessageBodyTypeVideo:
            {
                EMVideoMessageBody *body = (EMVideoMessageBody *)msgBody;
                
                NSLog(@"视频remote路径 -- %@"      ,body.remotePath);
                NSLog(@"视频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"视频的secret -- %@"        ,body.secretKey);
                NSLog(@"视频文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"视频文件的下载状态 -- %u"   ,body.downloadStatus);
                NSLog(@"视频的时间长度 -- %d"      ,body.duration);
                NSLog(@"视频的W -- %f ,视频的H -- %f", body.thumbnailSize.width, body.thumbnailSize.height);
                
                // 缩略图sdk会自动下载
                NSLog(@"缩略图的remote路径 -- %@"     ,body.thumbnailRemotePath);
                NSLog(@"缩略图的local路径 -- %@"      ,body.thumbnailLocalPath);
                NSLog(@"缩略图的secret -- %@"        ,body.thumbnailSecretKey);
                NSLog(@"缩略图的下载状态 -- %u"      ,body.thumbnailDownloadStatus);
            }
                break;
            case EMMessageBodyTypeFile:
            {
                EMFileMessageBody *body = (EMFileMessageBody *)msgBody;
                NSLog(@"文件remote路径 -- %@"      ,body.remotePath);
                NSLog(@"文件local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"文件的secret -- %@"        ,body.secretKey);
                NSLog(@"文件文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"文件文件的下载状态 -- %u"   ,body.downloadStatus);
            }
                break;
                
            default:
                break;
        }
    }
}


/** 下载数据*/
+ (void)postURL:(NSString*)url
      paramDict:(NSDictionary*)dict
     completion:(void (^)(NSDictionary *responseObject))completion
          error:(void (^)(NSError *error))errorHandler {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",IP,url];
    NSError *error;
    NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
    for (NSString *eachKey in [dict allKeys]) {
        [postDict setObject:[dict objectForKey:eachKey]
                     forKey:eachKey];
    }
    NSData *postStr = [NSJSONSerialization dataWithJSONObject:postDict
                                                      options:NSJSONWritingPrettyPrinted
                                                        error:&error];
    if (postStr != nil && error == nil) {
        
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"]) {
            [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"] forHTTPHeaderField:@"userToken"];
        }
        
        [manager POST:urlStr parameters:postDict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@ 当前线程  %@",url ,[NSThread currentThread]);
            
            NSError *error = nil;
            
            if ([self parseContentDict:responseObject error:&error]) {
                if (completion) {
                    
//                    NSDictionary *requestData = [[NSDictionary alloc] init];
//                    requestData = [responseObject objectForKey: @"obj"];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion(responseObject);
                    });
                }
                else {
                    if (errorHandler) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            errorHandler([NSError errorWithDomain:@"com.awcs.error.domain"
                                                             code:250250
                                                         userInfo:[NSDictionary dictionaryWithObjects:@[@"服务器返回数据格式错误，没有userInfo项"]
                                                                                              forKeys:@[NSLocalizedDescriptionKey]]]);
                        });
                    }
                }
            }
            else {
                if (errorHandler) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        errorHandler(error);
                    });
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (errorHandler) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    errorHandler(error);
                });
            }
        }];
        
    } else {
        if (errorHandler) {
            dispatch_async(dispatch_get_main_queue(), ^{
                errorHandler(error);
            });
        }
    }
}


/** 分析json数据*/
+ (BOOL)parseContentDict:(NSDictionary*)content error:(NSError**)error {
    
    if ([[content objectForKey:@"code"] intValue] == 0) {
        return YES;
    }
    else {
        int code = [[content objectForKey:@"code"] intValue];
        NSString *errorStr = [content objectForKey:@"errorMsg"];
        if(code == -999){
            
        }
        
        if (code == -888) {
            
            
        }
        
        if (error != nil) {
            if (errorStr.length == 0) {
                
                errorStr = [NSString stringWithFormat: @"code:%d,%@",code,@"提示为空"];
            }else if (code == 500) {
                errorStr = [NSString stringWithFormat: @"code:%d,服务器错误",code];
            } else if (code == 404) {
                errorStr = [NSString stringWithFormat: @"code:%d,找不到服务器",code];
            }
            *error = [NSError errorWithDomain:@"com.awcs.error.domain"
                                         code:code
                                     userInfo:[NSDictionary dictionaryWithObjects:@[errorStr]
                                                                          forKeys:@[NSLocalizedDescriptionKey]]];
        }
        return NO;
    }
}





@end
